package com.giscloud.generator.utils;

import com.alibaba.fastjson.JSON;
import com.giscloud.commons.annotation.AuthIgnore;
import com.giscloud.commons.annotation.SSOForceLoginAuth;
import com.giscloud.commons.annotation.SSOIgnore;
import com.giscloud.commons.codec.AESUtils;
import com.giscloud.commons.utils.CookieUtils;
import com.giscloud.commons.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author:giscloud
 * @Description:
 * @Date: 14:56 2019/9/3
 * @Modified By:
 */
public class InterceptorUtils {
    private final static Logger logger = LoggerFactory.getLogger(InterceptorUtils.class);

    public static boolean printMessage(HttpServletResponse response, String message, int code){
        response.setContentType("application/json; charset=utf-8");
        response.setCharacterEncoding("UTF-8");
        response.setStatus(200);
        PrintWriter pWriter = null;
        try {
            pWriter = response.getWriter();
            pWriter.write(JSON.toJSONString(R.error(message)));
        } catch (IOException e) {
            logger.debug("认证拦截器验证异常："+e.getMessage());
        } finally {
            if (pWriter != null) {
                pWriter.flush();
                pWriter.close();
            }
        }
        return false;
    }

    /**
     * Description ： 判断是否是Ajax请求
     *
     * @param request
     * @return
     */
    public static boolean isAjaxRequest(HttpServletRequest request) {
        String requestType = request.getHeader("X-Requested-With");
        if (StringUtils.isNotEmpty(requestType)) {
            return true;
        }
        requestType = request.getHeader("X-Requested-with");
        if (StringUtils.isNotEmpty(requestType)) {
            return true;
        }
        return false;
    }

    /**
     * 是否忽略认证，用户登录等信息
     *
     * @param handler
     * @return
     */
    public static boolean isIgnoreAuthentication(Object handler) {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            SSOIgnore methodAnnotation = handlerMethod.getMethodAnnotation(SSOIgnore.class);
            if (methodAnnotation == null) {
                return Boolean.FALSE;
            } else {
                return Boolean.TRUE;
            }
        } else {
            return Boolean.FALSE;
        }
    }

    /**
     * 是否忽略认证，用户权限等信息
     *
     * @param handler
     * @return
     */
    public static boolean isAuthIgnoreAuthentication(Object handler) {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            AuthIgnore methodAnnotation = handlerMethod.getMethodAnnotation(AuthIgnore.class);
            if (methodAnnotation == null) {
                return Boolean.FALSE;
            } else {
                return Boolean.TRUE;
            }
        } else {
            return Boolean.FALSE;
        }
    }

    /**
     * Description ： 自定义注解 是否强制验证
     * <p/>
     * 默认无注解 需要强制验证 有注解 不需要强制验证
     *
     * @param handler
     * @return
     */
    public static boolean isLoginAuthentication(Object handler) {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            SSOForceLoginAuth methodAnnotation = handlerMethod.getMethodAnnotation(SSOForceLoginAuth.class);
            if (methodAnnotation == null) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }
    /**
     * Description ： cookie解密
     *
     * @param request
     * @return
     */
    public static String decodeCookie(HttpServletRequest request, String cookieLoginUser, String cookieLoginPassword) {
        // 判断cookie中的值
        Cookie[] cookies = CookieUtils.getCookies(request);
        if (cookies == null) {
            return null;
        }
        String loginuserInfoStr = null;
        // cookiename是否失效
        String cookieValue = CookieUtils.getCookieValue(cookieLoginUser, request);
        if (StringUtils.isNotEmpty(cookieValue)) {
            loginuserInfoStr = AESUtils.decrypt2str(cookieValue, cookieLoginPassword);
            if (com.giscloud.commons.utils.StringUtils.isEmpty(loginuserInfoStr)) {
                return null;
            }
        } else {
            return null;
        }

        return loginuserInfoStr;
    }
}
